package com.woniu40.petai_manager.web;

import com.github.pagehelper.PageInfo;
import com.woniu40.petai_manager.entity.Brand;
import com.woniu40.petai_manager.entity.Goods;
import com.woniu40.petai_manager.entity.GoodsType;
import com.woniu40.petai_manager.entity.ProductType;
import com.woniu40.petai_manager.result.ResponseResult;

import com.woniu40.petai_manager.service.BrandService;
import com.woniu40.petai_manager.service.GoodsService;
import com.woniu40.petai_manager.service.GoodsTypeService;
import com.woniu40.petai_manager.service.ProductTypeService;
import com.woniu40.petai_manager.vo.GoodsVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("goods")
@Api("商品类")
@CrossOrigin
public class GoodsController {

    @Autowired
    BrandService brandService;

    @Autowired
    ProductTypeService productTypeService;

    @Autowired
    GoodsTypeService goodsTypeService;

    @Autowired
    GoodsService goodsService;

    @Value("${filepath}")
    String filepath;

    @PostMapping("/upload")
    @ResponseBody
    @ApiOperation("商品图片上传")
    public ResponseResult<String> upload(@RequestParam("cover") MultipartFile multipartFile){
        ResponseResult<String> result = new ResponseResult<>();
        String originalFilename = multipartFile.getOriginalFilename();
        String fileEnd = originalFilename.substring(originalFilename.indexOf("."));
        String fileName = "g_" + UUID.randomUUID().toString() + fileEnd;
        String path = filepath + File.separator + "product";
        File file = new File(path);
        if(!file.exists()){
            file.mkdirs();
        }
        try {
            multipartFile.transferTo(new File(path + File.separator + fileName));
            result.setCode(200);
            result.setMessage("上传成功！");
            result.setData(fileName);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            result.setCode(500);
            result.setMessage("上传失败！");
            return result;
        }
    }

    @GetMapping("/findAllTypes")
    @ResponseBody
    @ApiOperation("查询所有品牌，返回list集合")
    public ResponseResult<Map> findAllBrand(){
        ResponseResult<Map> result = new ResponseResult<>();
        List<Brand> brandList = brandService.findAllBrand();
        List<ProductType> productTypeList = productTypeService.findAllProductType();
        List<GoodsType> goodsTypeList = goodsTypeService.findAllGoodsType();
        Map map = new HashMap();
        map.put("brandList",brandList);
        map.put("productTypeList",productTypeList);
        map.put("goodsTypeList",goodsTypeList);
        result.setCode(200);
        result.setMessage("种类查询成功！");
        result.setData(map);
        return result;
    }


    @GetMapping("/goodsList")
    @ResponseBody
    @ApiOperation("分页查询商品列表")
    @ApiImplicitParams({@ApiImplicitParam(name="pageNum",value = "当前页",dataType = "int",paramType = "query",required = false),
            @ApiImplicitParam(name="pageSize",value = "页码数",dataType = "int",paramType = "query",required = false),
            @ApiImplicitParam(name="goodsName",value = "商品名称",dataType = "String",paramType = "query",required = false),
            @ApiImplicitParam(name="brand",value = "品牌ID",dataType = "int",paramType = "query",required = false),
    })
    public ResponseResult<PageInfo<GoodsVo>> goodsList(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
                                                       @RequestParam(value = "pageSize",defaultValue = "8") Integer pageSize,
                                                       @RequestParam(value = "goodsName",defaultValue = "") String goodsName,
                                                       @RequestParam(value = "brand",defaultValue = "0") Integer brand){
        ResponseResult<PageInfo<GoodsVo>> result = new ResponseResult<>();
        PageInfo<GoodsVo> pageInfo = goodsService.findGoodsByPage(pageNum, pageSize, goodsName, brand);
        result.setCode(200);
        result.setMessage("查询商品列表成功！");
        result.setData(pageInfo);
        return  result;
    }

    @PostMapping("/addGoods")
    @ResponseBody
    @ApiOperation("添加商品")
    public ResponseResult<String> addGoods(@RequestBody Goods goods, HttpServletRequest request){
        ResponseResult<String> result = new ResponseResult<>();
        goods.setSaleCount(0);
        Date date = new Date();
        goods.setCreateTime(date);
        //Integer userCode = (Integer) request.getSession().getAttribute("userCode");
        //Integer managerId = goodsService.findMidByCode(userCode);
        //goods.setManagerId(managerId);
        goods.setLastModifyTime(date);
        //goods.setModifyManagerId(managerId);
        GregorianCalendar gc =new GregorianCalendar();
        gc.setTime(goods.getProductTime());
        gc.add(5,goods.getShelfLife());
        Date expireDate = gc.getTime();
        goods.setExpireDate(expireDate);
        goodsService.addGoods(goods);
        result.setCode(200);
        result.setMessage("商品添加成功！");
        return result;
    }

    @PutMapping("/modifyGoods")
    @ResponseBody
    @ApiOperation("修改商品")
    public ResponseResult<String> modifyGoods(@RequestBody Goods goods){
        ResponseResult<String> result = new ResponseResult<>();
        int i = goodsService.modifyGoods(goods);
        result.setCode(200);
        result.setMessage("商品修改成功！");
        return result;
    }

    @DeleteMapping("/removeGoods")
    @ResponseBody
    @ApiOperation("根据id删除商品(可批量)")
    public ResponseResult<String> removeGoods(String ids){
        ResponseResult<String> result = new ResponseResult<>();
        if(ids.contains(",")){
            List<Integer> idList = new ArrayList<>();
            String[] idsStr = ids.split(",");
            for (String idStr : idsStr) {
                idList.add(Integer.valueOf(idStr));
            }
            int i = goodsService.removeByIds(idList);
        }else{
            Integer id = Integer.valueOf(ids);
            int i = goodsService.removeById(id);
        }
        result.setCode(200);
        result.setMessage("删除商品成功！");
        return result;
    }

    @GetMapping("/findGoodsById")
    @ResponseBody
    @ApiOperation("根据id查询商品对象")
    public ResponseResult<Goods> toModify(Integer goodsId){
        ResponseResult<Goods> result = new ResponseResult<>();
        Goods goods = goodsService.findGoodsById(goodsId);
        result.setCode(200);
        result.setMessage("查询成功！");
        result.setData(goods);
        return  result;
    }
}
